package com.sanjiahantang.youjiaclient.module.me.scheme.views.impl;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.R;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.DensityUtils;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.CircleImageView;
import com.sanjiahantang.uilibrary.views.MyListView;
import com.sanjiahantang.uilibrary.views.ObservableScrollView;
import com.sanjiahantang.uilibrary.views.supervideo.MediaController;
import com.sanjiahantang.uilibrary.views.supervideo.SuperVideoPlayer;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.config.StaticValue;
import com.sanjiahantang.youjiaclient.module.cases.views.impl.DesignerDetailActivity;
import com.sanjiahantang.youjiaclient.module.me.scheme.beans.MeCaseBean;
import com.sanjiahantang.youjiaclient.module.me.scheme.beans.MeCaseOBean;
import com.sanjiahantang.youjiaclient.module.me.scheme.presenters.MeSchemePresenter;
import com.sanjiahantang.youjiaclient.module.me.scheme.views.MeSchemeView;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.sanjiahantang.youjiaclient.videoplay.VideoPlayActivity;
import com.squareup.picasso.Picasso;

import java.util.List;

import com.sockect3d.Vedio_Activity;

import static android.os.Build.CPU_ABI;


/**
 * Created by zy on 2017/8/16.
 * 我的方案详情
 */

public class MeSchemeDetailActivity extends BaseMvpActivity<MeSchemeView, MeSchemePresenter> implements MeSchemeView, View.OnClickListener, ObservableScrollView.OnScrollChangedListener {
    private MeSchemeDetailActivity $this;
    private SuperVideoPlayer mSuperVideoPlayer;
    private View mPlayBtnView, inc, flVideo, flFavorite,txt3D;
    private ObservableScrollView svMainContent;
    private TextView title, txtRoomType, txtDesignerName, meZX;
    private MyListView lvInfo;
    private View rlDesigner, rlBack, fl_Left;
    private View containPanel, rlElse, ivGoOfTitle, ivFavoriteOfTitle;
    private String videoUrl = null;
    private MeCaseOBean.InformationListBean caseDetail;
    private ImageView ivHeader;

    private CircleImageView ivDesignerPhoto;


    private QuickAdapter<MeCaseBean.Detail> adapter;

    private String ppId, verSion, roamId = null;

    @Override
    public MeSchemePresenter initPresenter() {
        return new MeSchemePresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_case_detail);
        $this = this;
        mSuperVideoPlayer = (SuperVideoPlayer) findViewById(R.id.video_player_item_1);
        mPlayBtnView = findViewById(R.id.play_btn);
        inc = findViewById(R.id.inc);
        rlBack = findViewById(R.id.rlBack);
        flVideo = findViewById(R.id.mainTitle);
        findViewById(R.id.play_btn2).setOnClickListener(this);

        ivHeader = (ImageView) findViewById(R.id.ivHeader);
        svMainContent = (ObservableScrollView) findViewById(R.id.scroller);
        title = (TextView) findViewById(R.id.title);
        containPanel = findViewById(R.id.contentPanel);
        rlElse = findViewById(R.id.rlElse);
        txtRoomType = (TextView) findViewById(R.id.txtRoomType);
        txt3D = findViewById(R.id.txt3D);
        txtDesignerName = (TextView) findViewById(R.id.txtDesignerName);
        ivGoOfTitle = findViewById(R.id.icon1);
        ivFavoriteOfTitle = findViewById(R.id.icon2);
        lvInfo = (MyListView) findViewById(R.id.lvInfo);
        findViewById(R.id.flFavorite).setOnClickListener(this);
        findViewById(R.id.flFavorite).setVisibility(View.GONE);
        findViewById(R.id.flGo).setVisibility(View.GONE);
        ivDesignerPhoto = (CircleImageView) findViewById(R.id.ivDesignerPhoto);
        meZX = (TextView) findViewById(R.id.meZX);
        meZX.setOnClickListener(this);
        meZX.setText("报价详情");
        title.setText("案例详情");

        ppId = getIntent().getStringExtra(KEY_ID);
        verSion = getIntent().getStringExtra(KEY_VERSION);

        rlDesigner = findViewById(R.id.rlDesigner);
        rlDesigner.setOnClickListener(this);
        rlBack.setOnClickListener(this);
        txt3D.setOnClickListener(this);
        findViewById(R.id.fl_Left).setOnClickListener(this);
        svMainContent.setOnScrollChangedListener(this);
        presenter.setDetailCallBack(new DetailCallBack() {
            @Override
            public void loadData(MeCaseOBean.Data data) {
                //载入视频信息
                if (data.getInformationList().size() > 0) {
                    MeCaseOBean.InformationListBean detail = data.getInformationList().get(0);
                    List<MeCaseOBean.PicList> picList = data.getPicList();
                    for (MeCaseOBean.PicList pic : picList) {
                        if (pic.getPicCaId() == 15) {
                            videoUrl = pic.getUrl();
                            break;
                        }
                    }
                    //  videoUrl = "http://vod.cdn1.v.17173.com/295400817b3f772a00166e10964c5a00cd10d5ab660055b4/ra6/FLVList/20100121/sexycorn_612777_1.mp4";

                    if (!TextUtils.isEmpty(videoUrl)) {
                        //               findViewById(R.id.play_btn2).setVisibility(View.VISIBLE);
//                    findViewById(R.id.play_btn2).setOnClickListener(this);
                    }

                    if (TextUtils.isEmpty(detail.getRoamId())){
                        txt3D.setVisibility(View.GONE);
                        roamId = null;
                    }else{
                        txt3D.setVisibility(View.VISIBLE);
                        roamId = detail.getRoamId();
                    }
                    txtRoomType.setText(detail.getLikeStyleName() + " , "
                            + detail.getApartmentTypeName() + " , "
                            + detail.getApartmentArea() + "㎡");
                    txtDesignerName.setText(detail.getDesignRoleName());
                    Picasso.with($this).load(FileUtils.rePath(detail.getUrl())).placeholder(R.drawable.i_match).into(ivDesignerPhoto);
                    //shipin
                    if (videoUrl != null) {
                        //  String url = detail.getUrl();
                        //   if (detail.getUrl().indexOf("http") != 0) {
                        //        url = ConfigValue.IMG_IP + url;
                        //    }
                        Picasso.with($this).load(videoUrl)
                                .placeholder(R.drawable.i_match)
                                .error(R.drawable.i_match)
                                .into(ivHeader);
                    } else {
                        ivHeader.setImageResource(R.drawable.i_match);
                    }
                    caseDetail = detail;
                    if (detail.getVersion() == null || "0".equals(detail.getVersion())){
                        meZX.setVisibility(View.INVISIBLE);
                    }else{
                        meZX.setVisibility(View.VISIBLE);
                    }
                } else {
                    finish();
                    Utils.showToast($this, "没有找到方案");
                }

            }

            @Override
            public void initAdapter(QuickAdapter adapter) {
                lvInfo.setAdapter(adapter);
            }

            @Override
            public void loadVersion(String version) {
                verSion = version;
            }
        });
        presenter.loadCaseById($this, ppId);
    }

    @Override
    public void initData() {
        mPlayBtnView.setOnClickListener(this);
        mSuperVideoPlayer.setVideoPlayCallback(mVideoPlayCallback);
        inc.setVisibility(View.GONE);
    }

    @Override
    public void onBackPressed() {
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            this.getResources().getConfiguration().orientation = Configuration.ORIENTATION_PORTRAIT;
            mVideoPlayCallback.onSwitchPageType();
            return;
        }
        super.onBackPressed();

    }

    @Override
    public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {

        if (Utils.checkIsVisible(this, rlBack)) {
            showTitleView(View.GONE);
        } else {
            showTitleView(View.VISIBLE);
            if (Utils.checkIsVisible(this, rlElse)) {
                ivGoOfTitle.setVisibility(View.GONE);
                ivFavoriteOfTitle.setVisibility(View.GONE);
            } else {
//                ivGoOfTitle.setVisibility(View.VISIBLE);
//                ivFavoriteOfTitle.setVisibility(View.VISIBLE);
            }

        }
    }

    private void showTitleView(int state) {
        inc.setVisibility(state);
//        ivGoOfTitle.setVisibility(state);
//        ivFavoriteOfTitle.setVisibility(state);
    }


    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    /**
     * 播放器的回调函数
     */
    private SuperVideoPlayer.VideoPlayCallbackImpl mVideoPlayCallback = new SuperVideoPlayer.VideoPlayCallbackImpl() {
        /**
         * 播放器关闭按钮回调
         */
        @Override
        public void onCloseVideo() {
            mSuperVideoPlayer.close();//关闭VideoView
            mPlayBtnView.setVisibility(View.VISIBLE);
            mSuperVideoPlayer.setVisibility(View.GONE);
            resetPageToPortrait();
        }

        /**
         * 播放器横竖屏切换回调
         */
        @Override
        public void onSwitchPageType() {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                mSuperVideoPlayer.setPageType(MediaController.PageType.SHRINK);
                containPanel.setVisibility(View.VISIBLE);
                rlElse.setVisibility(View.VISIBLE);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                mSuperVideoPlayer.setPageType(MediaController.PageType.EXPAND);
                containPanel.setVisibility(View.GONE);
                rlElse.setVisibility(View.GONE);


            }
        }

        /**
         * 播放完成回调
         */
        @Override
        public void onPlayFinish() {

        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlDesigner:
                if (caseDetail != null) {
                    startActivity(new Intent($this, DesignerDetailActivity.class)
                            .putExtra(KEY_PHONE, caseDetail.getDesignRoleId())
                            .putExtra(KEY_ID, caseDetail.getId())
                    );
                }

                break;
            case R.id.rlBack:
                finish();
                break;
            case R.id.fl_Left:
                finish();
                break;
            case R.id.flFavorite:
                //    presenter.addCollectInfo(this,id);
                break;

            case R.id.meZX://报价清单
                presenter.checkISPlanceOrder($this, ppId, verSion);
                break;
            case R.id.play_btn2:
                if (videoUrl == null) {
                    Utils.showToast($this, "无法加载该视频");
                    return;
                }

                Intent intent = new Intent(this, VideoPlayActivity.class);
                intent.putExtra(VideoPlayActivity.TRANSITION, true);
                intent.putExtra(StaticValue.VIDEO_URL, videoUrl);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    Pair pair = new Pair<>(view, VideoPlayActivity.IMG_TRANSITION);
                    ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
                            this, pair);
                    ActivityCompat.startActivity(this, intent, activityOptions.toBundle());
                } else {
                    startActivity(intent);
                    overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
                }
                break;
            case R.id.txt3D:
                if(TextUtils.isEmpty(roamId)){
                    Utils.showToast($this,"没有3D漫游方案");
                }else{
                    Vedio_Activity.startActivity($this,roamId);
                }
                break;
            default:
                if (videoUrl == null) {
                    Utils.showToast($this, "无法加载该视频");
                    return;
                }
                mPlayBtnView.setVisibility(View.GONE);
                mSuperVideoPlayer.setVisibility(View.VISIBLE);
                mSuperVideoPlayer.setAutoHideController(false);
                Uri uri = Uri.parse(videoUrl);
                mSuperVideoPlayer.loadAndPlay(uri, 0);
                break;
        }

    }

    /***
     * 旋转屏幕之后回调
     *
     * @param newConfig newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (null == mSuperVideoPlayer) return;
        /***
         * 根据屏幕方向重新设置播放器的大小
         */
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().getDecorView().invalidate();
            float height = DensityUtils.getWidthInPx(this);
            float width = DensityUtils.getHeightInPx(this);
            mSuperVideoPlayer.getLayoutParams().height = (int) width;
            mSuperVideoPlayer.getLayoutParams().width = (int) height;
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
//            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            float width = DensityUtils.getWidthInPx(this);
            float height = DensityUtils.dp2px(this, 200.f);
            mSuperVideoPlayer.getLayoutParams().height = (int) height;
            mSuperVideoPlayer.getLayoutParams().width = (int) width;
        }
    }

    /***
     * 恢复屏幕至竖屏
     */

    private void resetPageToPortrait() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mSuperVideoPlayer.setPageType(MediaController.PageType.SHRINK);
        }
    }
}

